import { useEffect, useRef, useState } from "react";

const UseRefDemo = () => {
  return <>
    <ClickCounter />
    <TimerRef />
  </>;
};


const ClickCounter = () => {
  const countRef = useRef(0); // 初始值为 0
  const [displayCount, setDisplayCount] = useState(0);

  const handleClick = () => {
    // 更新 ref 的值（不会触发重新渲染）
    countRef.current += 1;
    console.log("🚀 ~ handleClick ~ countRef:", countRef);

    // 可选：更新 state 以触发 UI 更新
    if (countRef.current % 10 === 0) {
      setDisplayCount(countRef.current);
    }
  };

  return (
    <div>
      <button onClick={handleClick}>点击我</button>
      <p>实际计数（ref）: {countRef.current}</p>
      <p>显示: {displayCount}</p>
      <p>只有点击的次数是10的倍数时，才更新显示state</p>
    </div>
  );
};

const TimerRef = () => {
  const timerRef = useRef<null | number>(null); // 保存定时器 ID
  const [timer, setTimer] = useState(0);

  useEffect(() => {
    timerRef.current = setInterval(() => {
      console.log('定时器运行中...');
      setTimer(timer + 1);
    }, 1000);

    // 清除定时器
    return () => {
      if (timerRef.current)
        clearInterval(timerRef.current);
    };
  });

  return <div>
    <h1> {timer}</h1>
  </div>;
};

export default UseRefDemo;